﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace WindowsAzure_StorageREST.FileBlob
{
    public class FileBlobStore
    {
        public const uint MaxFileNameLength = 255;

        /// <summary>
        /// Allowed file metadata
        /// </summary>
        public enum EnumFileMetaData
        {
            FileName,
            Attributes,
            CreationTimeUtc,
            LastAccessTimeUtc,
            LastWriteTimeUtc,
            RelativePath,
            PathWithName,
            Size,
            IsDirectory
        }

        public static bool GetRelativePath(string rootDirectory, string filePath, out string relativePath)
        {
            relativePath = String.Empty;
            DirectoryInfo directory = new DirectoryInfo(rootDirectory);         
            FileInfo file = new FileInfo(filePath);          
            string fullDirectory = directory.FullName;         
            string fullFile = file.FullName;          
            if (!fullFile.StartsWith(fullDirectory))         
            {             
                return false;       
            }

            relativePath = fullFile.Substring(fullDirectory.Length + 1);
            return true;
        }

        // Create the name value collection of associated file metadata for the given blob.
        public static void SetupMetadata(
            string rootDirectory,
            string filePath,
            Dictionary<string, string> metaData
            )
        {
            FileInfo fileInfo = new FileInfo(filePath);

            // Create metadata to be associated with the blob 
            metaData[EnumFileMetaData.FileName.ToString()] = fileInfo.FullName;
            metaData[EnumFileMetaData.Attributes.ToString()] = ((long)fileInfo.Attributes).ToString();
            metaData[EnumFileMetaData.CreationTimeUtc.ToString()] = fileInfo.CreationTimeUtc.ToString();
            metaData[EnumFileMetaData.LastAccessTimeUtc.ToString()] = fileInfo.LastAccessTimeUtc.ToString();
            metaData[EnumFileMetaData.LastWriteTimeUtc.ToString()] = fileInfo.LastWriteTimeUtc.ToString();

            string relativePath = String.Empty;

            if (FileBlobStore.GetRelativePath(rootDirectory, filePath, out relativePath) 
                && !String.IsNullOrEmpty(relativePath))
            {
                metaData[EnumFileMetaData.RelativePath.ToString()] = relativePath;
            }
            metaData[EnumFileMetaData.PathWithName.ToString()] = filePath;
            metaData[EnumFileMetaData.Size.ToString()] = fileInfo.Length.ToString();
            metaData[EnumFileMetaData.IsDirectory.ToString()] = Directory.Exists(filePath).ToString();
        }
    }
}
